<template>
	<view class="search-result-list-container">
		<empty-data v-if="isEmpty" />
		<!-- 1. 通过 mescroll-body 包裹列表，指定 ref 为 mescrollRef ，监听@init、@down、@up 事件 -->
		<mescroll-body ref="mescrollRef" @init="mescrollInit" @down="downCallback" @up="upCallback">
			<block v-for="(item, index) in resultList" :key="index">
				<view class="search-result-item-box" @click="onItemClick(item)">
					<search-result-item-theme-1 v-if="!item.pic_list || item.pic_list.length === 0" :data='item' />
					<search-result-item-theme-2 v-else-if="item.pic_list.length === 1" :data="item" />
					<search-result-item-theme-3 v-else :data="item" />
				</view>
			</block>
		</mescroll-body>
	</view>
</template>

<script>
	// 2. 导入对应的 mixins
	import MescrollMixin from '@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js';
	import { _getSearchResult } from 'api/search.js'
	export default {
		name: "search-result-list",
		mixins: [MescrollMixin],
		props: {
			queryStr: {
				type: String,
				required: true
			}
		},
		data() {
			return {
				page: 1, // 页数
				resultList: [],
				isInit: true,
				isEmpty: false // 是否无数据
			};
		},
		methods: {
			/**
			 * 获取搜索数据
			 */
			async loadSearchResult() {
				const { data: res } = await _getSearchResult({
					q: this.queryStr,
					p: this.page
				})
				// 更改返回数据样式（行内样式）
				res.list.forEach(item => {
					//  /g 全局替换
					item.title = item.title.replace(/<em>/g, "<em style='color:#f94d2a; margin:0 2px'>")
					item.description = item.description.replace(
						/<em>/g,
						"<em style='color:#f94d2a; margin:0 2px'>"
					);
				})
				// 无数据，显示空数据组件
				if (this.page === 1) {
					this.resultList = res.list
				} else {
					this.resultList = [...this.resultList, ...res.list];
				}
				if (this.resultList.length === 0) {
					this.isEmpty = true;
				}
			},
			// 4. 实现三个回调方法
			/**
			 * 首次加载
			 */
			async mescrollInit() {
				this.isInit = false;
				await this.loadSearchResult();
				// 结束 上拉加载 && 下拉刷新
				this.mescroll.endSuccess();
			},
			/**
			 * 下拉刷新的回调
			 */
			async downCallback() {
				if (this.isInit) return;
				this.page = 1;
				await this.loadSearchResult();
				// 结束 上拉加载 && 下拉刷新
				this.mescroll.endSuccess();
			},
			/**
			 * 上拉加载的回调
			 */
			async upCallback() {
				if (this.isInit) return;
				this.page += 1
				await this.loadSearchResult()
				this.mescroll.endSuccess();
			},
			onItemClick(item) {
				console.log(item)
				uni.navigateTo({
					url: `/subpkg/pages/blog-detail/blog-detail?author=${item.author}&articleId=${item.id}`
				})
			}
		},
		created() {
			//   不需要主动调用
			// this.loadSearchResult()
		},
		mounted() {
			// 通过 $refs 获取组件实例
			this.mescroll = this.$refs.mescrollRef.mescroll;
		}
	}
</script>

<style lang="scss" scoped>
	.search-result-list-container {
		padding: $uni-spacing-col-lg $uni-spacing-row-lg;

		.search-result-item-box {
			margin-bottom: $uni-spacing-col-big;
		}
	}
</style>
